<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require APPPATH . 'controllers/kint/Kint.class.php';

class Manage extends CI_Controller {

	public $user_emails = array();
	function __construct() {
		parent::__construct();
		$this->is_logged_in();
	}

	
	function my_tasks(){
		$data['tasks'] = $this->tasks_model->get_all();
		$this->load->model('users_model');
		$data['username'] = $this->get_username();
		$data['userid'] = $this->get_user_id();
		$data['main_content'] = 'tasks/my-tasks.php';
		$this->load->view('includes/template.php',$data);
	}

	function load_add_new_task($valid = false){

		$data['username'] = $this->get_username();
		$this->load->model('users_model');
		$data['users'] = $this->users_model->get_all_users();
		$data['valid'] = $valid;
		$data['main_content'] = 'create_task.php';
		$this->load->view('includes/template.php',$data);
	}

    function create_task(){

        $this->load->library('form_validation');
        $this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean');
        $this->form_validation->set_rules('content', 'Task Description', 'required');
        $this->form_validation->set_rules('date', 'Date Due', 'required|xss_clean');
		$this->form_validation->set_rules('status', 'Status', 'required|xss_clean');
		$this->form_validation->set_rules('priority', 'Priority', 'required|xss_clean');
        $this->form_validation->set_rules('responsible', 'Responsible', 'required');
        $this->form_validation->set_rules('accountable', 'Accountable', 'required');
        $this->form_validation->set_error_delimiters('<div class="col-sm-6"><div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>', '</div></div>');
        if ($this->form_validation->run() == FALSE){
            $this->load_add_new_task();
        }else{
            $title = $this->input->post('title');
            $this->load->model('users_model');
            $user_id =  $this->get_user_id();
            $url = $this->create_url($title);
            $this->load->helper('htmlpurifier');
            $pure_title = html_purify($title);
            date_default_timezone_set('GMT');
            $data = array(
                    'title' => $pure_title,
                    'url' => strtolower(url_title($title)),
                    'content' => $this->input->post('content'),
                    'date_due' => date('Y-m-d',strtotime($this->input->post('date'))),
                    'responsible' => count($this->input->post('responsible')) > 0 ? json_encode($this->input->post('responsible')) : '',
                    'accountable' => count($this->input->post('accountable')) > 0 ? json_encode($this->input->post('accountable')) : '',
                    'consulted' => count($this->input->post('consulted')) > 0 ? json_encode($this->input->post('consulted')) : '',
                    'informed' => count($this->input->post('informed')) > 0 ? json_encode($this->input->post('informed')) : '',
                    'user_id' => $user_id,
                    'priority' => $this->input->post('priority'),
                    'status' => $this->input->post('status')
            );
            $this->email_employees($data);
            $this->load->model('tasks_model');
            $query = $this->tasks_model->insert($data);
            if ($query) {
                    $this->load_add_new_task(true);
            }

        }
	}

    public function title_check($title){
            $title_test = preg_match("/[^a-z0-9-]+/i", strip_tags($title));
            if ( !$title_test ){
                    $this->form_validation->set_message('title_check', 'The %s field has invalid characters.');
                    return FALSE;
            }else{
                    return TRUE;
            }
    }

	function manage_tasks(){
		$this->load->model('users_model');
		$data['username'] = $this->get_username();
		$data['user_id'] = $this->get_user_id();
		$this->load->model('tasks_model');
		$data['tasks'] = $this->tasks_model->get_tasks_from_user($this->get_user_id());
		$data['main_content'] = 'tasks/manage-tasks.php';
		$this->load->view('includes/template.php',$data);

	}

	function is_logged_in(){
		$is_logged_in = $this->session->userdata('is_logged_in');
		if (!isset($is_logged_in) || $is_logged_in != true) {
			redirect('/');
			die();
		}
	}

	function logout(){
		redirect('/login');
		$this->session->sess_destroy();
	}

	function get_username(){
		$session = $this->session->all_userdata();
		return $session['username'];
	}

	function get_user_id(){
		$session = $this->session->all_userdata();
		return $session['id'];
	}


	function reload_task($task_id){
		$this->load->model('users_model');
		$this->load->model('comments');
		$data['username'] = $this->get_username();
		$data['user_id'] = $this->get_user_id();

		$data['task'] = $this->tasks_model->get_single_task_by_id($task_id);
		$data['comments'] = $this->comments->get_comments($data['task']->id);
		$data['main_content'] = 'view_task';
		$this->load->view('includes/template.php',$data);
	}

	function create_url($text){
		$friendlyURL = htmlentities(strip_tags($text), ENT_COMPAT, "UTF-8", false); 
	    $friendlyURL = preg_replace('/&([a-z]{1,2})(?:acute|lig|grave|ring|tilde|uml|cedil|caron);/i','\1',$friendlyURL);
	    $friendlyURL = html_entity_decode($friendlyURL,ENT_COMPAT, "UTF-8"); 
	    $friendlyURL = preg_replace('/[^a-z0-9-]+/i', '-', $friendlyURL);
	    $friendlyURL = preg_replace('/-+/', '-', $friendlyURL);
	    $friendlyURL = trim($friendlyURL, '-');
	    $url = strtolower($friendlyURL);
	    return $text;
	}

	function email_employees($task){
		
		$this->load->library('email');

		$this->load->model('users_model');
		$title = $task['title'];
		$url = 'http://raci.logzil.la:5780/'.$task['url'];
		$content =  substr($task['content'], 0 , 250) . '<a href="'.$url.'">Read More</a>';

		$responsible = $this->users_model->get_user_info(json_decode($task['responsible']));
		$accountable = $this->users_model->get_user_info(json_decode($task['accountable']));
		$consulted = $this->users_model->get_user_info(json_decode($task['consulted']));
		$informed = $this->users_model->get_user_info(json_decode($task['informed']));
		
		$responsible_role = (is_array($responsible))? $this->get_roles('Responsible: ',$responsible) : false;
		$accountable_role = (is_array($accountable))? $this->get_roles('Accountable: ',$accountable) : false;
		$consulted_role = (is_array($consulted))? $this->get_roles('Consulted: ',$consulted) : false;
		$informed_role =(is_array($informed))?  $this->get_roles('Informed: ',$informed) : false;

		$emails = array();
		$responsible_email = (is_array($responsible))?$this->get_emails($responsible) : false;
		$accountable_email = (is_array($accountable))?$this->get_emails($accountable) : false;
		$consulted_email = (is_array($consulted))?$this->get_emails($consulted) : false;
		$informed_email = (is_array($informed))?$this->get_emails($informed) : false;
		$emails = array_unique(array_merge((is_array($responsible_email)) ? $responsible_email : array(), (is_array($accountable_email)) ? $accountable_email : array(), (is_array($consulted_email)) ? $consulted_email : array(), (is_array($informed_email)) ? $informed_email : array()));
		$email_recepients = implode(', ', $emails);

		$message = '';
		$message .= '<p><strong>Task:</strong> ' .$title. '</p>';
		$message .= '<p><strong>Task URL:</strong> <a href="'.$url.'">'.$url.'</a>'. '</p>';
		$message .= '<p><strong>Employees Responsible</strong> :'.$responsible_role. '</p>';
		$message .= '<p><strong>Employees Accountable</strong> :'.$accountable_role. '</p>';
		$message .= '<p><strong>Employees Consulted</strong> :'.$consulted_role. '</p>';
		$message .= '<p><strong>Employees Informed</strong> :'.$informed_role. '</p>';
		$message .= '<div><p><strong>Task Description</strong> :</p> ' .$content . '</div>';
		$this->email->set_mailtype("html");
                $message = '';
                        $message .= '<p><strong>Task:</strong> ' .$title. '</p>';
                        $message .= '<p><strong>Task URL:</strong> <a href="'.$url.'">'.$url.'</a>'. '</p>';
                                $message .= '<p><strong>Employees Responsible</strong> :'.$responsible_role. '</p>';
                                $message .= '<p><strong>Employees Accountable</strong> :'.$accountable_role. '</p>';
                                        $message .= '<p><strong>Employees Consulted</strong> :'.$consulted_role. '</p>';
                                        $message .= '<p><strong>Employees Informed</strong> :'.$informed_role. '</p>';
                                                $message .= '<div><p><strong>Task Description</strong></p>: '.$content . '</div>';
		$this->email->from('raci@logzilla.net', 'RACI Task Manager');
		$this->email->to($email_recepients); 
		
		$this->email->subject('A task has been assigned to you.');
		$this->email->message($message); 
		$this->email->send();

	}


	function get_roles($role, $users){
		$names = array();
		foreach ($users as $user) {
			array_push($names, $user->name);
		}
		return implode(', ', $names);
	}

	function get_emails($users){
		$emails = array();
		foreach ($users as $user) {
			array_push($emails, $user->email);
		}
		return $emails;
	}


	function add_comment(){
		
		$this->load->model('comments');
		$comment = array(
			'user_id' => $this->input->post('user_id'),
			'task_id' => $this->input->post('task_id'),
			'comment' => $this->input->post('comment')
		);
		
		$query = $this->comments->insert($_POST);

		if ($query) {
			$this->reload_task($comment['task_id']);
		}
	
	}


}

/* End of file manage.php */
/* Location: ./application/controllers/manage.php */
